package main

import (
	"bytes"
	"gitee.com/hlwqds/rabitmqTest/log"
	"github.com/streadway/amqp"
	syslog "log"
	"time"
)

func main(){
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	log.FailOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	log.FailOnError(err, "Failed to open a channel")
	defer ch.Close()

	//意味着消费者未确认的数据最多只能有一个。因此可以保证一个消费者不会有远多于另一个消费者的未处理任务。
	err = ch.Qos(
		1,
		0,
		false)
	log.FailOnError(err, "Failed to set QoS")

	//在此声明队列，因为有可能我们会在生产者启动之前启动消费者
	q, err := ch.QueueDeclare(
		"helloDurable",
		//队列持久化
		true,
		false,
		false,
		false,
		nil)
	log.FailOnError(err, "Failed to declare a queue")
	msgs, err := ch.Consume(
		q.Name,
		"",
		false,
		false,
		false,
		false,
		nil)
	log.FailOnError(err, "Failed to register a consumer")

	forever := make(chan bool)
	go func(){
		for d := range msgs {
			syslog.Printf("Received a message: %s", d.Body)
			dotCount := bytes.Count(d.Body, []byte("."))
			t := time.Duration(dotCount)
			time.Sleep(t * time.Second)
			syslog.Printf("Done")
			d.Ack(false)
		}
	}()
	syslog.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}